document.addEventListener('DOMContentLoaded', function() {
    const loginForm = document.getElementById('loginForm');
    const errorMessage = document.getElementById('errorMessage');

    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password }),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('登录失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.type === 'admin') {
                    window.location.href = 'admin.html';
                } else if (data.type === 'user') {
                    // 存储用户ID到本地存储，用于后续操作
                    localStorage.setItem('userId', data.userId);
                    window.location.href = 'user.html';
                } else {
                    showError('登录失败：未知用户类型');
                }
            })
            .catch(error => {
                console.error('登录出错:', error);
                showError('登录失败，请稍后再试');
            });
    });

    function showError(message) {
        errorMessage.textContent = message;
        errorMessage.style.display = 'block';
        setTimeout(() => {
            errorMessage.style.display = 'none';
        }, 5000);
    }
});